package com.nf.health.app.inquiry.docdetail;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.login.activity.LoginActivity;
import com.nf.health.app.core.MyGsonBuilder;
import com.nf.health.app.customview.DividerListItemDecoration;
import com.nf.health.app.http.Act;
import com.nf.health.app.inquiry.adapter.HomeServiceDescriptAdapter;
import com.nf.health.app.inquiry.adapter.SelectServiceDataTypeAdapter;
import com.nf.health.app.inquiry.bean.DoctorDetailBean;
import com.nf.health.app.inquiry.bean.MySeltctPayTime;
import com.nf.health.app.inquiry.bean.PayParamsModel;
import com.nf.health.app.inquiry.bean.SubsDirect;
import com.nf.health.app.inquiry.impl.viewholder.DoctorOrderPayHolder;
import com.nf.health.app.models.DoctorCommnetVo;
import com.nf.health.app.models.ServicreDateType;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.GetToast;
import com.nf.health.app.utils.JsonUtils;
import com.nf.health.app.utils.ModelUtils;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.Util;
import com.nf.health.app.utils.ViewUtil;
import com.nf.health.app.widget.MyMainItemAnimation;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 家庭服务自费说明
 *
 * @author yyh
 * @date 2016-09-28
 */
public class DocHomeOrderActivity extends BaseActivity implements DoctorOrderPayHolder.OnMyClickLintener {
    public final static String DOCTORID = "com.nf.homeservicediscriptactivity.doctorId";
    @Bind(R.id.swipe_home_descript_refresh_layout)
    SwipeRefreshLayout swipe_home_descript_refresh_layout;
    @Bind(R.id.recyclerView_doc_descript)
    RecyclerView recyclerView_doc_descript;
    @Bind(R.id.titlebar_title_tv)
    TextView titlebar_title_tv;
    @Bind(R.id.btn_odc_order_service)
    Button btn_odc_order_service;//订购服务
    @Bind(R.id.gv_order_date)
    GridView gv_order_date;

    @Bind(R.id.tv_doctor_goodness_doc_price)
    TextView tv_doctor_goodness_doc_price;//订购所附方式总格
    private List<MySeltctPayTime> list2 = new ArrayList<>();//服务选择类型
    private HomeServiceDescriptAdapter homeServiceDescriptAdapter;
    private String doctorId = "2016010816545959080910";
    private List<DoctorCommnetVo> doctorCommnetVoList;
    private String buyservice = "1";// 1未购买 2 已购买
    private String type = "1";
    private String isOpen = "0";//	判断是否打开服务	string	-1功能不存在，0未开启，1已开启
    private SelectServiceDataTypeAdapter myAdapter;
    private int selectdataTypePosition = 0;//默认选中第一条
    private DoctorDetailBean doctorDetailBean;//得到医生的头像的基本信息

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_homeservicediscript);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        swipe_home_descript_refresh_layout.setColorSchemeResources(R.color.theme_color, android.R.color.holo_red_light, android.R.color.holo_green_light, android.R.color.holo_orange_light);
        recyclerView_doc_descript.setHasFixedSize(true);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        recyclerView_doc_descript.setLayoutManager(mLayoutManager);
        recyclerView_doc_descript.setItemAnimator(new MyMainItemAnimation());
        homeServiceDescriptAdapter = new HomeServiceDescriptAdapter(this, null);
        recyclerView_doc_descript.setAdapter(homeServiceDescriptAdapter);

        recyclerView_doc_descript.addItemDecoration(new DividerListItemDecoration(DocHomeOrderActivity.this, LinearLayoutManager.VERTICAL, 1,
                getResources().getColor(R.color.divider_line_color)));
        swipe_home_descript_refresh_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // swipe_home_descript_refresh_layout.setRefreshing(true);
                loadBaseDocDetail();
            }
        });
        titlebar_title_tv.setText("医生详情");
        homeServiceDescriptAdapter.regisitOnClickListener(this);
        btn_odc_order_service.setOnClickListener(this);
        doctorId = getIntent().getStringExtra(Constants.DOCTOR_ID);
    }

    private void loadBaseDocDetail() {
        provider.getDoctorServiceDetai(doctorId, type);
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        switch (actionName) {
            case Act.Flag.DOC_DETAIL:
                DoctorDetailBean doctorDetail = (DoctorDetailBean) object;
                break;
            case Act.Flag.GETDOCTORSERVICESETTINGDETAIL_FLAG:
                swipe_home_descript_refresh_layout.setRefreshing(false);
                isOpen = JsonUtils.getFiledData(object.toString(), "open");
                String doctorDetailBeanStr = JsonUtils.getFiledData(object.toString(), "doctor");
                String ServicreDateTypeStr = JsonUtils.getFiledData(object.toString(), "services");
                Gson gson = new MyGsonBuilder().createGson();
                doctorDetailBean = gson.fromJson(doctorDetailBeanStr, new TypeToken<DoctorDetailBean>() {
                }.getType());
                homeServiceDescriptAdapter.setMyHeaderDocDetail(doctorDetailBean);
                ServicreDateType servicreDateType = gson.fromJson(ServicreDateTypeStr, new TypeToken<ServicreDateType>() {
                }.getType());
                buyservice = servicreDateType.getBuyservice();
                if (servicreDateType.getExplains() != null) {
                    List<SubsDirect> subsDirect = servicreDateType.getExplains();
                    homeServiceDescriptAdapter.setDoctorCommentData(subsDirect);
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        homeServiceDescriptAdapter.notifyDataSetChanged();
                    }
                });
                list2.clear();
                list2 = ModelUtils.getMyAllServiceList(servicreDateType);
                loadServiceDataType(list2);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_odc_order_service:
                if (!Util.isLogin()) {
                    ActivityUtils.showActivity(this, LoginActivity.class);
                    return;
                }
                if (!TextUtils.isEmpty(buyservice)) {// 1未购买 2 已购买
                    boolean isLogin = PreferenceHelper.getBoolean(PreferenceHelper.ISLOGIN, true);
                    if (!isLogin) {
                        ActivityUtils.skipActivity(this, LoginActivity.class);
                        return;
                    }
                    if (TextUtils.isEmpty(buyservice)) {// 1未购买 2 已购买
                        return;
                    } else if (buyservice.equals("2")) {
                        GetToast.useString(DocHomeOrderActivity.this, "当前服务未结束");
                        return;
                    } else if (buyservice.equals("1")) {
                        Bundle docDetailBundle = new Bundle();
                        PayParamsModel payParamsModel = new PayParamsModel();
                        docDetailBundle.putSerializable(Constants.DOCTOR_NEED_PARAMS, payParamsModel);
                        if (doctorDetailBean != null) {
                            payParamsModel.setDoctorName(doctorDetailBean.getDoctorname());
                            payParamsModel.setHeadImg(doctorDetailBean.getDoctorhimg());
                            payParamsModel.setServiceTrpe("家庭医生服务");
                            payParamsModel.setDoctorId(doctorId);
                        }
                        if (list2.size() > 0) {
                            MySeltctPayTime mySeltctPayTime = list2.get(selectdataTypePosition);
                            float fPrice = Float.parseFloat(mySeltctPayTime.getMoney());
                            fPrice = (float) (fPrice * 0.01);
                            payParamsModel.setServiceMoney(String.valueOf(fPrice));
                            payParamsModel.setServicTime(mySeltctPayTime.getSelestDate());

                        }
                        ActivityUtils.showActivity(this, PayOrderServiceActivity.class, docDetailBundle);
                    }
                    break;

                }
        }
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        super.handleActionError(actionName, response, error);
        switch (actionName) {
            case Act.Flag.DOC_DETAIL_COMMEMNT:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadBaseDocDetail();
        homeServiceDescriptAdapter.regisitOnClickListener(this);
    }

    @Override
    public void goToPayMoneyOrderService(Object obj) {
        GetToast.useString(DocHomeOrderActivity.this, obj.toString());
    }

    /**
     * 加载底选择服务类型的时间
     */
    private void loadServiceDataType(final List<MySeltctPayTime> list2) {
        if (list2 == null) {
            return;
        }
        if (myAdapter == null) {
            myAdapter = new SelectServiceDataTypeAdapter(this, list2);
            gv_order_date.setAdapter(myAdapter);
            if (list2.size() > 0) {
                list2.get(0).setIsClick(true);
                gv_order_date.setSelection(0);
                ViewUtil.setPriceTextView(tv_doctor_goodness_doc_price, list2.get(0).getMoney());
            }
        } else {
            myAdapter.setMyNotifyDataChanged(list2);
            if (list2.size() > 0) {//防止刷新的时候设置为无数据
                list2.get(selectdataTypePosition).setIsClick(true);
                ViewUtil.setPriceTextView(tv_doctor_goodness_doc_price, list2.get(selectdataTypePosition).getMoney());
            }
        }
        gv_order_date.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MySeltctPayTime mySelectpayTime = list2.get(position);
                selectdataTypePosition = position;
                mySelectpayTime.setIsClick(true);
                ModelUtils.dealNotSelectStatus(list2, position, myAdapter);
                ViewUtil.setPriceTextView(tv_doctor_goodness_doc_price, list2.get(position).getMoney());
            }
        });
    }
}
